package main

import (
	"context"
	"golang.org/x/sync/semaphore"
	"sync"
)

type Task int

func handle1(tasks []Task, execute func(task Task)) {
	wg := sync.WaitGroup{}
	sema := semaphore.NewWeighted(10)
	ctx := context.TODO()
	for i, _ := range tasks {
		wg.Add(1)
		task := tasks[i]
		go func() {
			defer func() {
				wg.Done()
				sema.Release(1)
			}()
			// execute task
			err := sema.Acquire(ctx, 1)
			if err != nil {
				panic(err)
			}
			execute(task)
		}()
	}
	wg.Wait()
}

func handle(tasks []Task, execute func(task Task)) {
	wg := sync.WaitGroup{}
	ch := make(chan struct{}, 10)
	for i, _ := range tasks {
		ch <- struct{}{}
		wg.Add(1)
		task := tasks[i]
		go func() {
			defer wg.Done()
			// execute task
			execute(task)
			<-ch
		}()
	}
	wg.Wait()
}
